#!/usr/bin/env python3

# Copyright (c) 2020-2021 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


import os
import mrget
import subprocess
from ._util import Util, TempChdir, ActionRunner
from ._const import Const
from ._errors import BuildError
from ._device import DeviceManager
from ._settings import Settings, TargetSettings
from ._manifest import Manifest


class Builder(ActionRunner):

    def __init__(self, settings, target_settings, work_dir):
        assert Settings.check_object(settings, raise_exception=False)
        assert isinstance(target_settings, TargetSettings) and target_settings.check(raise_exception=False)

        self._s = settings
        if self._s.log_dir is not None:
            os.makedirs(self._s.log_dir, mode=0o750, exist_ok=True)

        self._ts = target_settings

        self._workDirObj = work_dir
        self._workDirObj.save_device_and_attach_addon(self._ts.os_version, self._ts.device_id)

        actionList = [
            self.action_initialize,
            self.action_fetch_source,
            self.action_build,
            self.action_install_core_applications,
            self.action_cleanup,
        ]

        def x(self, action_name, action, extra_run=0):
            s = self._getActionIndex("action_" + action_name)
            actionSubList = self._actionList[s:s + extra_run + 1]
            # check
            if extra_run > 0:
                for i, action in enumerate(actionSubList):
                    assert action._action is not None and not action._action.is_exclusive()
            # prepare
            for i, action in enumerate(actionSubList):
                action._action.prepare(action._action_func_name, self._s, self._ts, self._workDirObj)
            # run
            vm = None
            try:
                for i, action in enumerate(actionSubList):
                    vm = action._action.run(action._action_func_name, self._s, self._ts, self._workDirObj, reuse_vm=vm)
                if vm is not None:
                    vm.wait_until_stable_then_shutdown()
                    vm.wait_until_stop()
            except BaseException:
                if vm is not None:
                    vm.poweroff()
                    vm.wait_until_stop()
                raise

        super().__init__(self._workDirObj._persistentStorage, actionList, x, BuildError)

    @ActionRunner.Action()
    def action_initialize(self):
        p = DeviceManager.getPreBuildImagesObject(self._ts.device_id)
        if p.has_image(self._ts.os_version):
            # jump over the following actions: fetch_source, build
            assert False
            return

        curPath = self._workDirObj.get_latest_action_dirpath()

        # initialize ".repo" directory
        mainUrl = mrget.target_urls(Const.MAIN_URL)[0]
        Util.callRepo(curPath, "init", ["-u", mainUrl, "-b", "lineage-%s" % (self._ts.os_version), "--git-lfs"])

        # modify manifest files
        m = Manifest(os.path.join(curPath, ".repo"), "manifest.xml")
        if True:
            aospGitUrl = mrget.target_urls("mirror://aosp-git")[0]
            lineageGitUrl = mrget.target_urls("mirror://lineageos-git")[0]
            if True:
                m.get_remote("github").remove_self()
                m.get_remote("private").remove_self()
            if True:
                r = m.get_remote(name="aosp")
                r["fetch"] = aospGitUrl
                Util.dictForceDelete(r, "review")
            if True:
                m2 = m.get_include("manifests/default.xml")
                m2.add_remote(name="lineage", fetch=lineageGitUrl)
                m2.get_defaults()["remote"] = "lineage"
                for p in m2.get_projects():
                    if p["remote"]["name"] == "lineage":
                        assert p["name"].startswith("LineageOS/")
                        p["name"] = p["name"][len("LineageOS/"):]
            m.save()

    @ActionRunner.Action(after=["initialize"])
    def action_fetch_source(self):
        with TempChdir(self._workDirObj.get_latest_action_dirpath()):
            subprocess.check_call(["repo", "sync"])

    @ActionRunner.Action(after=["fetch_source"])
    def action_build(self):
        with TempChdir(self._workDirObj.get_latest_action_dirpath()):
            subprocess.check_call(["croot"])
            subprocess.check_call(["brunch", "XXXX"])

    @ActionRunner.Action(after=["build"])
    def action_install_core_applications(self):
        pass

    @ActionRunner.Action(after=["build", "install_core_applications"])
    def action_cleanup(self):
        pass

    def add_custom_actions(self, action_dict, insert_after=None, insert_before=None):
        for action in action_dict.values():
            assert action.check_object(action, raise_exception=False)
        super().add_custom_actions(action_dict, insert_after, insert_before)

    def _getQuiet(self):
        return (self._s.verbose_level == 0)
